#include "QtOgreApplication.h"
#include "ui_mainwindow.h"
#include "ui_settings.h"

#include "strings.h"


QtOgreApplication::QtOgreApplication(QWidget *parent) :
	m_OgreRoot (new Ogre::Root("","")),
	QMainWindow(parent),
	ui(new Ui::MainWindow)
{
	// Start the mainwindow UI
	ui->setupUi(this);

	// Initialize Ogre
	InitOgre();

	// Create a new QOgreWidget
	m_GameWidget = new GameWidget(m_OgreRoot, this);

	// Set WindowTitle
	this->setWindowTitle(QString::fromStdString(Strings::TITLE));

	// Make the QOgreWidget the CentralWidget
	this->setCentralWidget(m_GameWidget);

	// Get Focus and show maximized
	//this->showFullScreen();
	this->showMaximized();

} // constructor

void QtOgreApplication::InitOgre()
{
	// This is where we store all the needed PluginNames
	std::vector<Ogre::String> PluginNames;

	PluginNames.push_back("RenderSystem_GL");
	PluginNames.push_back("Plugin_ParticleFX");

	// Save path to ogre pluginfolder
	Ogre::String pluginpath = "";

#if defined(__gnu_linux__)
	pluginpath.append("/usr/local/lib/OGRE/");
#endif

	for (std::vector<Ogre::String>::iterator iter = PluginNames.begin(); iter != PluginNames.end(); iter++)
	{
		// Check if we are in debug mode an load correct libraries (only on WIN32)
#if defined(_DEBUG)
		(*iter).append("_d");
#endif

		m_OgreRoot->loadPlugin(pluginpath+(*iter));
	}


	// look for the openGL renderer in Ogre
	Ogre::RenderSystemList::const_iterator availableRendererIt = m_OgreRoot->getAvailableRenderers().begin();
	while(availableRendererIt != m_OgreRoot->getAvailableRenderers().end())
	{
		Ogre::String rName = (*availableRendererIt)->getName();
		if (rName == "OpenGL Rendering Subsystem")
		{
			break;
		}
		++availableRendererIt;
	}

	if (availableRendererIt == m_OgreRoot->getAvailableRenderers().end())
	{
		throw std::runtime_error("We were unable to find the OpenGL renderer in ogre's list, cannot continue");

	}



	// use the OpenGL renderer in the root config
	m_OgreRenderSystem = *availableRendererIt;
	m_OgreRoot->setRenderSystem( m_OgreRenderSystem );
	m_OgreRoot->initialise(false);
}

QtOgreApplication::~QtOgreApplication()
{
	delete m_OgreRoot;
	delete m_GameWidget;

	delete ui;

} // destructor


void QtOgreApplication::on_actionClose_triggered()
{
	this->close();
}

void QtOgreApplication::on_actionSettings_triggered()
{
	QDialog *settings = new QDialog(0,0);
	Ui_Settings SettingsUi;
	SettingsUi.setupUi(settings);

	settings->show();
}
